package com.softWang.common.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.softWang.common.handler.BigLongSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Configuration
public class GlobalConfig {
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        //configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080")); // 允许的源
        configuration.setAllowedOrigins(Arrays.asList("*")); // 允许的源为*时，setAllowCredentials(false)必须false
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的方法
        configuration.setAllowedHeaders(Arrays.asList("*")); // 允许的头部
        configuration.setAllowCredentials(false); // 允许凭据

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); // 对所有路径生效
        return source;
    }

    //解决LocalDateTime序列化问题，spring.jackson.date-format=yyyy-MM-dd HH:mm:ss针对的是java.util.Date，LocalDateTime需要单独配置
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        return builder -> {
            // 配置LocalDateTime 序列化、反序列化规则
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            builder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            // 新增 Long 类型序列化规则，数值超过 2^53-1，在 JS 会出现精度丢失问题，因此 Long 自动序列化为字符串类型,已解决雪花id在js中精度丢失问题
            builder.serializerByType(Long.class, BigLongSerializer.INSTANCE);
            builder.serializerByType(Long.TYPE, BigLongSerializer.INSTANCE);
            // 其他配置
            builder.timeZone("GMT+8");
        };
    }
}
